/*
 * @Author: your name
 * @Date: 2021-09-15 09:34:48
 * @LastEditTime: 2022-09-23 16:18:31
 * @LastEditors: zshawk1982
 * @Description: In User Settings Edit
 * @FilePath: \media_system\routes\article.js
 */
const { Sequelize } = require("sequelize");
const { Knowledge, Recipe, Food } = require("../database/index");
const Router = require("@koa/router");
const { formatResponse, resizeImg,filterColumn } = require("../utils/common");
const uploadLocal = require('../utils/uploadLocal');
const { uploadQiniu, getFileUrl } = require('../utils/uploadQiNiu');
const Redis = require("ioredis");
const redis = new Redis();
const router = new Router();
// 配置user路由

/**
 * @swagger
 * /knowledge/getKnowledgeDetailByAdmin:
 *   get:
 *     security:
 *       - bearerAuth: []
 *     summary: 根据知识ID查询知识详细信息-服务端
 *     description: 根据知识ID查询知识详细信息-服务端
 *     tags: [知识]
 *     parameters:
 *       - name: knowledgeId
 *         in: query #参数存放位置。query是存放到请求头里边
 *         required: true
 *         description: 知识ID
 *         type: string
 *     responses:
 *       200:
 *         description: 成功
 */
router.get("/getKnowledgeDetailByAdmin", async function (ctx, next) {
  const { knowledgeId } = ctx.request.query;
  let knowledgeDetail = await Knowledge.findOne({ 
    where: { knowledgeId } });

  //更新redis中的浏览量
  // redis.hincrby('knowledgeviews', knowledgeId, 1)

  if (knowledgeDetail) {
    ctx.body = formatResponse("200", { ...knowledgeDetail.get({ plain: true }) }, "success");
  } else {
    ctx.body = formatResponse("500", "", "fail");
  }
});

/**
 * @swagger
 * /knowledge/getKnowledgeDetail:
 *   get:
 *     security:
 *       - bearerAuth: []
 *     summary: 根据知识ID查询知识详细信息
 *     description: 根据知识ID查询知识详细信息
 *     tags: [知识]
 *     parameters:
 *       - name: knowledgeId
 *         in: query #参数存放位置。query是存放到请求头里边
 *         required: true
 *         description: 知识ID
 *         type: string
 *     responses:
 *       200:
 *         description: 成功
 */
router.get("/getKnowledgeDetail", async function (ctx, next) {
  const { knowledgeId } = ctx.request.query;
  let knowledgeDetail = await Knowledge.findOne({ 
    attributes:['createdAt','updatedAt','knowledgeId','title','type','avator','views','content','weight'],
    where: { knowledgeId } });

    // console.log(11111111111,knowledgeId)
  //更新redis中的浏览量
  await redis.hincrby('knowledgeviews', knowledgeId, 1)

  if (knowledgeDetail) {
    ctx.body = formatResponse("200", { ...knowledgeDetail.get({ plain: true }) }, "success");
  } else {
    ctx.body = formatResponse("500", "", "fail");
  }
});


/**
 * @swagger
 * /knowledge/getAllKnowledge:
 *   get:
 *     security:
 *       - bearerAuth: []
 *     summary: 查询所有知识
 *     description: 查询所有知识
 *     tags: [知识]
 *     responses:
 *       200:
 *         description: 成功
 */
router.get("/getAllKnowledge", async function (ctx, next) {
  let knowledges = await Knowledge.findAll();
  if (knowledges) {
    ctx.body = formatResponse("200", knowledges, "success");
  } else {
    ctx.body = formatResponse("500", "", "fail");
  }
});
/**
 * @swagger
 * /knowledge/getKnowledgesAndRecipesAndFoodsByName:
 *   get:
 *     security:
 *       - bearerAuth: []
 *     summary: 根据名称查询知识和食谱和食物
 *     description: 根据名称查询知识和食谱和食物
 *     tags: [知识]
 *     parameters:
 *       - name: name
 *         in: query #参数存放位置。query是存放到请求头里边
 *         description: 知识标题或者食谱名称或者食物名称
 *         type: string
 *     responses:
 *       200:
 *         description: 成功
 */
router.get("/getKnowledgesAndRecipesAndFoodsByName", async function (ctx, next) {
  const Op = Sequelize.Op;
  const { name } = ctx.request.query;
  const condition1 = name ? { foodName: { [Op.like]: `%${name}%` } } : null;
  const condition2 = name ? { title: { [Op.like]: `%${name}%` } } : null;
  const condition3 = name ? { recipeName: { [Op.like]: `%${name}%` } } : null;
  const results = await Promise.all([
    Recipe.findAll({
      where: Object.assign({}, condition3)
    }),
    Knowledge.findAll({
      where: Object.assign({}, condition2)
    }),
    Food.findAll({
      where: Object.assign({}, condition1)
    }),
  ]).then((modelReturn) => {
    return modelReturn //第一个数组是食谱数组，第二个数组是知识数组，第三个数组是食物数组
  })
  if (results) {
    ctx.body = formatResponse("200", results, "success");
  } else {
    ctx.body = formatResponse("500", "", "fail");
  }
});
/**
 * @swagger
 * /knowledge/getKnowledgesByPageAndCondition:
 *   get:
 *     security:
 *       - bearerAuth: []
 *     summary: 条件分页查询知识
 *     description: 条件分页查询知识
 *     tags: [知识]
 *     parameters:
 *       - name: title
 *         in: query #参数存放位置。query是存放到请求头里边
 *         description: 知识标题
 *         type: string
 *       - name: type
 *         in: query #参数存放位置。query是存放到请求头里边
 *         description: 知识类型（0血糖 1饮食 2其他）
 *         type: integer
 *       - name: createdAts
 *         in: query #参数存放位置。query是存放到请求头里边
 *         description: 发布时间段
 *         schema:
 *          type: array
 *          items:
 *            type: string
 *       - name: currentPage
 *         in: query #参数存放位置。query是存放到请求头里边
 *         required: true
 *         description: 当前第几页
 *         type: string
 *       - name: pageSize
 *         in: query #参数存放位置。query是存放到请求头里边
 *         required: true
 *         description: 一页几条记录
 *         type: string
 *     responses:
 *       200:
 *         description: 成功
 */
router.get("/getKnowledgesByPageAndCondition", async function (ctx, next) {
  const Op = Sequelize.Op;
  const { currentPage, pageSize, title, type, createdAts } = ctx.request.query;
  offset = (currentPage - 1) * pageSize || 0;
  //条件1：知识标题
  //条件2：知识类型（0血糖 1饮食 2其他）
  //条件3：发布时间（几月几日到几月几日）
  const condition1 = title ? { title: { [Op.like]: `%${title}%` } } : null;
  const condition2 = type ? { type: { [Op.eq]: type } } : null;
  const condition3 = createdAts ? createdAts.length > 0 ? { 'createdAt': { [Op.between]: createdAts } } : null : null;
  let result = await Knowledge.findAndCountAll({
    attributes:['createdAt','updatedAt','knowledgeId','title','summary','type','views','logoImg','weight'],
    where: Object.assign({}, condition1, condition2, condition3),
    order: [['weight', 'DESC'],['createdAt', 'DESC']],
    offset,
    limit: parseInt(pageSize),
  });
  if (result) {
    ctx.body = formatResponse("200", result, "success");
  } else {
    ctx.body = formatResponse("500", "", "fail");
  }
});
/**
 * @swagger
 * /knowledge/add: #接口访问路径(拼接上之前swagger.js中的host)
 *   post: #请求方式
 *     summary: 添加知识信息  #接口信息
 *     description: 添加知识信息 #接口描述
 *     tags: [知识] #接口分组
 *     produces:
 *       - application/json
 *     requestBody:
 *         content:
 *            multipart/form-data:
 *               schema:
 *                  type: object
 *                  required:
 *                  - title
 *                  - content
 *                  - type
 *                  - avator
 *                  properties:
 *                     title:          
 *                        type: string
 *                        description: 知识名称
 *                     summary:          
 *                        type: string
 *                        description: 摘要
 *                     content:          
 *                        type: string
 *                        description: 知识内容
 *                     type:          
 *                        type: integer
 *                        enum: [ "0", "1", "2"]
 *                        description: 知识类型（0血糖 1饮食 2其他）
 *                     views:          
 *                        type: integer
 *                        description: 浏览量
 *                     weight:          
 *                        type: integer
 *                        description: 权重（文章排序标识，值越大，越靠前）
 *                     avator:          
 *                        type: string
 *                        format: binary
 *                        description: 知识标题封面
 *     responses: #返回结果
 *       200:
 *         description: 成功
 */
router.post("/add", async function (ctx, next) {
  let err = await uploadLocal.single('avator')(ctx, next).then(res => res).catch(err => err)
  if (err) {
    // console.log(err)
    ctx.body = formatResponse("500", {
      code: 0,
      msg: err.message
    }, "fail");
  } else {
    let knowledgeInfo = ctx.request.body;
    //完成图片logo的缩放和转换成base64
    const data64str = await resizeImg(ctx.file)
    //完成七牛云上传
    try {
      const result = await uploadQiniu(ctx.file).catch((error) => {
        throw error
      })
      knowledgeInfo = { ...knowledgeInfo, logoImg: data64str, avator: getFileUrl(result.respBody.key) }
      let currentKnowledge = await Knowledge.create({
        ...knowledgeInfo,
      });
      currentKnowledge = currentKnowledge.get({ plain: true })
      // console.log(1111111111111,currentKnowledge)
      //新增知识向redis中新增
      await redis.hset('knowledgeviews',currentKnowledge.knowledgeId,currentKnowledge.views||1)

      if (currentKnowledge) {
        ctx.body = formatResponse("200", { ...currentKnowledge }, "success");
      } else {
        ctx.body = formatResponse("500", { message: '数据库存储失败' }, "fail");
      }
    } catch (error) {
      ctx.body = formatResponse("500", error, "fail");
    }

  }

});
/**
 * @swagger
 * /knowledge/imageAdd: #接口访问路径(拼接上之前swagger.js中的host)
 *   post: #请求方式
 *     summary: 多图片上传  #接口信息
 *     description: 多图片上传 #接口描述
 *     tags: [知识] #接口分组
 *     produces:
 *       - application/json
 *     requestBody:
 *         content:
 *            multipart/form-data:
 *               schema:
 *                  type: object
 *                  required:
 *                  - files
 *                  properties:
 *                     files:   
 *                      description: 图片数组
 *                      type: array
 *                      items:       
 *                        type: string
 *                        format: binary
 *                        description: 知识标题封面
 *     responses: #返回结果
 *       200:
 *         description: 成功
 */
router.post("/imageAdd", async function (ctx, next) {

  let err = await uploadLocal.array('files')(ctx, next)
    .then(res => res)
    .catch(err => err)
  if (err) {
    ctx.body = formatResponse("500", {
      code: 0,
      msg: err.message
    }, "fail");
  } else {
    let actions = []
    for (let i = 0; i < ctx.files.length; i++) {
      let action = uploadQiniu(ctx.files[i])
      actions.push(action);  // 将每次循环调用的方法添加到方法数组中
    }
    try {
      const imgPaths = []
      const imgs = await Promise.all(actions).then((res) => {
        return res
      }).catch((error) => {
        throw error
      })
      if (imgs.length > 0) {
        imgs.forEach((i) => {
          imgPaths.push(getFileUrl(i.respBody.key))
        })
      }
      ctx.body = formatResponse("200", { code: 200, message: '多图片上传成功', payload: imgPaths }, "success");
    } catch (error) {
      ctx.body = formatResponse("500", error, "fail");
    }
  }

});
/**
 * @swagger
 * /knowledge/deleteKnowledge:
 *   get:
 *     security:
 *       - bearerAuth: []
 *     summary: 根据知识ID删除知识
 *     description: 根据知识ID删除知识
 *     tags: [知识]
 *     parameters:
 *       - name: knowledgeIds
 *         in: query #参数存放位置。query是存放到请求头里边
 *         required: true
 *         description: 知识ID
 *         schema:
 *          type: array
 *          items:
 *            type: string
 *     responses:
 *       200:
 *         description: 成功
 */
router.get("/deleteKnowledge", async function (ctx, next) {
  let { knowledgeIds } = ctx.request.query;
  const count = await Knowledge.destroy({
    where: {
      knowledgeId: knowledgeIds
    }
  });

  //删除记录同时从redis中删除对应的记录
  for(let i=0;i<knowledgeIds.length;i++){
    let result = await redis.hexists('knowledgeviews',knowledgeIds[i])
    if(result){
      await redis.hdel('knowledgeviews',knowledgeIds[i])
    }
  }

  if (count > 0) {
    ctx.body = formatResponse("200", "", "success");
  } else {
    ctx.body = formatResponse("500", "", "fail");
  }
});

/**
 * @swagger
 * /knowledge/updateKnowledge: #接口访问路径(拼接上之前swagger.js中的host)
 *   post: #请求方式
 *     security:
 *       - bearerAuth: []
 *     summary: 根据知识ID更新知识信息  #接口信息
 *     description: 根据知识ID更新知识信息 #接口描述
 *     tags: [知识] #接口分组
 *     produces:
 *       - application/json
 *     consumes:
 *       - application/json
 *     requestBody:
 *         content:
 *            multipart/form-data:
 *               schema:
 *                  type: object
 *                  required:
 *                  - knowledgeId
 *                  properties:
 *                     knowledgeId:          # <!--- form field name
 *                        type: string
 *                        description: 知识ID
 *                     title:          
 *                        type: string
 *                        description: 知识名称
 *                     summary:          
 *                        type: string
 *                        description: 摘要
 *                     content:          
 *                        type: string
 *                        description: 知识内容
 *                     type:          
 *                        type: integer
 *                        enum: [ "0", "1", "2"]
 *                        description: 知识类型（0血糖 1饮食 2其他）
 *                     weight:          
 *                        type: integer
 *                        description: 权重（文章排序标识，值越大，越靠前）
 *                     views:          
 *                        type: integer
 *                        description: 浏览量
 *                     avator:          
 *                        type: string
 *                        format: binary
 *                        description: 知识标题封面
 *     responses: #返回结果
 *       200:
 *         description: 成功
 */
router.post("/updateKnowledge", async function (ctx, next) {
  let err = await uploadLocal.single('avator')(ctx, next).then(res => res).catch(err => err)
  if (err) {
    ctx.body = formatResponse("500", {
      code: 0,
      message: '上传图片故障' + err.message
    }, "fail");
  } else {
    //本地上传正常的情况下
    try {
      let knowledgeInfo = ctx.request.body;
      knowledgeInfo = filterColumn(knowledgeInfo)

      if (ctx.file) {
        //完成图片logo的缩放和转换成base64
        const data64str = await resizeImg(ctx.file)
        //完成七牛云上传
        let qiniuImg = await uploadQiniu(ctx.file).catch((error) => {
          throw error
        })
        knowledgeInfo = { ...knowledgeInfo, logoImg: data64str, avator: getFileUrl(qiniuImg.respBody.key) }
      }
      let result = await Knowledge.update(
        {
          ...knowledgeInfo
        },
        {
          where: {
            knowledgeId: knowledgeInfo.knowledgeId,
          },
        }
      );
      if (result[0] > 0) {
        ctx.body = formatResponse("200", { code: 200, message: '知识更新成功' }, "success");
      } else {
        ctx.body = formatResponse("500", { code: 500, message: '知识更新失败' }, "fail");
      }

    } catch (error) {
      ctx.body = formatResponse("500", error, "fail");
    }
  }

});

module.exports = router;
